import React, {Component} from 'react';
import './css/lifecycle.css'

class App extends Component {
    ref = React.createRef();

    state = {
        list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    }

    getSnapshotBeforeUpdate(prevProps, prevState) {
        return [this.ref.current.scrollTop, this.ref.current.scrollHeight];
    }

    // getSnapshotBeforeUpdate的返回值当做第3个参数snapshot
    componentDidUpdate(prevProps, prevState, snapshot) {
        // scrollTop: 滚动条当前位置距离顶部的长度   scrollHeight: 滚动条总长度
        this.ref.current.scrollTop = snapshot[0] + this.ref.current.scrollHeight - snapshot[1];
    }

    render() {
        return (<div>
            <h1>React Study</h1>
            <button onClick={() => this.setState({list: [...[11,12,13,14,15], ...this.state.list]})}>click</button>
            <div ref={this.ref} style={{height:'200px', width:'200px', overflow:'auto', backgroundColor:'yellow'}}>
                <ul>
                    {this.state.list.map(item => <li style={{height: '100px'}} key={item}>{item}</li>)}
                </ul>
            </div>
        </div>);
    }
}

export default App;